// 这个是TCP/IP客户端-服务器中的客户端程序
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include <unistd.h>

#define CLIT_PROT 8888

int main(int argc, char *argv[]){
	struct sockaddr_in serv_addr; // 这里为服务器的地址结构
	int clit_fd,ret,i;
	char buf[1024];
	
	//1. 创建套接字
	clit_fd = socket(AF_INET,SOCK_STREAM,0);
	if(clit_fd == -1){
		printf("套接字创建失败!\n");
		exit(-1);
	}

	//2. 使用connect函数进行连接
	bzero(&serv_addr,sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(CLIT_PROT);
	inet_pton(AF_INET, "127.0.0.1", (struct in_addr*)&serv_addr.sin_addr.s_addr);
	//serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	
	ret = connect(clit_fd,(struct sockaddr *)&serv_addr, sizeof(serv_addr));
	if(ret == -1){
		printf("connect连接失败!\n");
		exit(-1);
	}
	
	while(1){
		bzero(buf,sizeof(buf));
		scanf("%s",buf);
		ret = write(clit_fd,buf,sizeof(buf));
		if(ret == -1){
			printf("数据写入失败!\n");
			exit(-1);
		}
		
		ret = read(clit_fd,buf,sizeof(buf));
		if(ret == -1){
			printf("数据读取失败!\n");
			exit(-1);
		}
		write(STDOUT_FILENO,buf,ret);
		printf("\n");
		
	}
	//3. 使用read()函数进行读取
	//4. 使用write()函数进行写入
	//5. 关闭套接字
	close(clit_fd);

}

